package de.tuberlin.swt.prog2.httpserver;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	private final int port;

	public Server(final int port) {
		this.port = port;
	}
	
	public void start() {
		ServerSocket server = null;
		try {
			server = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}

		System.out.println("Server started.");
		while (true) {
			Socket client = null;
			try {
				client = server.accept();
				System.out.println("Accepted client.");
				handleClient(client);
				System.out.println("  Done.");
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				close(client);
			}
		}
	}
	
	private void handleClient(final Socket client) {
		BufferedReader input = null;
		BufferedWriter output = null;
		try {
			input = new BufferedReader(new InputStreamReader(client
					.getInputStream()));
			output = new BufferedWriter(new OutputStreamWriter(client
					.getOutputStream()));
			final String request = input.readLine();
			HttpHelper.handleRequest(input, output, request);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			close(output);
			close(input);
		}
	}

	private void close(final Reader reader) {
		if (reader != null) {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void close(final Writer writer) {
		if (writer != null) {
			try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void close(final Socket client) {
		if (client != null) {
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		Server server = new Server(8888);
		server.start();
	}

}
